package com.hanxu.mallproduct.service.impl;

import com.hanxu.mallproduct.dao.CategoryBrandRelationDao;
import com.hanxu.mallproduct.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanxu.common.utils.PageUtils;
import com.hanxu.common.utils.Query;

import com.hanxu.mallproduct.dao.BrandDao;
import com.hanxu.mallproduct.entity.BrandEntity;
import com.hanxu.mallproduct.service.BrandService;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) throws UnsupportedEncodingException {
        // 获取key

        String key = (String)params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(key)) {
            String tmpKey=URLDecoder.decode(key, "UTF-8");
            wrapper.eq("brand_id", tmpKey).or().like("name", tmpKey);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void updateDetail(BrandEntity brand) {
        // 保证冗余字段的数据一致
        this.updateById(brand);
        if (!StringUtils.isEmpty(brand.getBrandId())) {
            categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());
            //TODO 以后更新其他关联
        }
    }

}